package javaee.cglib;

import javaee.aspect.MyAspect;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    public Object createProxy(Object target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        MyAspect aspect = new MyAspect();
        
        // 前置增强
        aspect.checkPermissions();
        
        // 执行目标方法
        Object result = methodProxy.invokeSuper(proxy, args);
        
        // 后置增强
        aspect.log();
        
        return result;
    }
}
